package com.fly.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fly.persistence.DataEntity;
import org.apache.commons.lang3.StringUtils;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Fly
 * @Description
 * @Date Created in 14:35 2018/1/29
 * @Modified by
 */
@Entity
@Table(name = "sys_role")
public class Role extends DataEntity<Role> {

    /**
     * 角色名
     */
    @NotNull(message = "角色名不能为空")
    @Size(max = 20)
    @Column(nullable = false,length = 20,unique = true)
    private String name;


    @ManyToMany(cascade = CascadeType.DETACH, fetch = FetchType.EAGER)
    @JoinTable(name = "sys_role_menu", joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "menu_id", referencedColumnName = "id"))
    private List<Menu> menuList = new ArrayList<>();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @JsonIgnore
    public List<Menu> getMenuList() {
        return menuList;
    }

    public void setMenuList(List<Menu> menuList) {
        this.menuList = menuList;
    }

    @JsonIgnore
    public List<Long> getMenuIdList() {
        List<Long> menuIdList = new ArrayList<>();
        for (Menu menu : menuList) {
            menuIdList.add(menu.getId());
        }
        return menuIdList;
    }

    public void setMenuIdList(List<String> menuIdList) {
        menuList = new ArrayList<>();
        for (String menuId : menuIdList) {
            Menu menu = new Menu();
            menu.setId(Long.valueOf(menuId));
            menuList.add(menu);
        }
    }

    public String getMenuIds() {
        return StringUtils.join(getMenuIdList(), ",");
    }

    public void setMenuIds(String menuIds) {
        menuList = new ArrayList<>();
        if (menuIds != null){
            String[] ids = StringUtils.split(menuIds, ",");
            setMenuIdList(Arrays.asList(ids));
        }
    }
}
